package com.lovegu.two;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.io.*;
import java.net.Socket;

/**
 * <p>
 * 基于 JavaFx 实现文字聊天室-客户端
 * </p>
 *
 * @author 老顾
 * @since 2023/3/29
 */
public class ChatRoomClient extends Application {
    private String serverIP;
    private int serverPort;
    private String userName;

    private Socket socket;
    private DataInputStream inputStream;
    private DataOutputStream outputStream;

    private TextArea chatArea;
    private TextField inputField;
    private Button sendButton;

    @Override
    public void start(Stage primaryStage) {

        // 创建登录界面
        Label serverLabel = new Label("服务器:");
        TextField serverField = new TextField();
        serverField.setText("localhost");
        Label portLabel = new Label("端口:");
        TextField portField = new TextField();
        portField.setText("8888");
        Label nameLabel = new Label("用户名:");
        TextField nameField = new TextField();
        Button loginButton = new Button("登录");

        VBox loginBox = new VBox();
        loginBox.setSpacing(10);
        loginBox.getChildren().addAll(serverLabel, serverField, portLabel, portField, nameLabel, nameField, loginButton);
        loginBox.setAlignment(Pos.CENTER);

        Scene loginScene = new Scene(loginBox, 300, 250);

        // 创建聊天界面
        chatArea = new TextArea();
        chatArea.setEditable(false);
        chatArea.setWrapText(true);
        inputField = new TextField();
        sendButton = new Button("发送");
        sendButton.setDisable(true);

        HBox inputBox = new HBox();
        inputBox.setSpacing(10);
        inputBox.getChildren().addAll(inputField, sendButton);
        inputBox.setAlignment(Pos.CENTER);

        BorderPane chatPane = new BorderPane();
        chatPane.setCenter(chatArea);
        chatPane.setBottom(inputBox);

        Scene chatScene = new Scene(chatPane, 400, 400);

        // 设置登录按钮的事件处理器
        loginButton.setOnAction(event -> {
            serverIP = serverField.getText();
            serverPort = Integer.parseInt(portField.getText());
            userName = nameField.getText();

            // 尝试连接服务器
            try {
                socket = new Socket(serverIP, serverPort);
                inputStream = new DataInputStream(socket.getInputStream());
                outputStream = new DataOutputStream(socket.getOutputStream());

                // 发送用户名给服务器
                outputStream.writeUTF(userName);

                // 切换到聊天界面
                primaryStage.setScene(chatScene);
                primaryStage.setTitle("聊天室 - " + userName);

                // 启动接收消息的线程
                Thread receiveThread = new Thread(() -> {
                    try {
                        while (true) {
                            String message = inputStream.readUTF();
                            Platform.runLater(() -> chatArea.appendText(message + "\n"));
                        }
                    } catch (IOException e) {
                        Platform.runLater(() -> {
                            Alert alert = new Alert(Alert.AlertType.ERROR, "连接已断开");
                            alert.showAndWait();
                            primaryStage.setScene(loginScene);
                            primaryStage.setTitle("登录");
                        });
                    }
                });
                receiveThread.setDaemon(true);
                receiveThread.start();

                // 启用发送按钮
                sendButton.setDisable(false);
                inputField.requestFocus();
            } catch (IOException e) {
                Alert alert = new Alert(Alert.AlertType.ERROR, "连接失败");
                alert.showAndWait();
            }
        });

        // 设置发送按钮的事件处理器
        sendButton.setOnAction(event -> {
            String message = inputField.getText();
            if (!message.isEmpty()) {
                try {
                    outputStream.writeUTF(message);
                    inputField.setText("");
                } catch (IOException e) {
                    Alert alert = new Alert(Alert.AlertType.ERROR, "发送失败");
                    alert.showAndWait();
                }
            }
        });

        primaryStage.setScene(loginScene);
        primaryStage.setTitle("登录");
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
